package com.wnn.demo.model.task.controller;

import com.github.pagehelper.PageInfo;
import com.wnn.demo.domain.*;
import com.wnn.demo.model.system.service.UserService;
import com.wnn.demo.model.task.service.AccessoryService;
import com.wnn.demo.model.task.service.FeedbackService;
import com.wnn.demo.model.task.service.TaskService;
import com.wnn.demo.pojo.Result;
import com.wnn.demo.pojo.ResultCode;
import com.wnn.demo.utils.IdGen;
import com.wnn.demo.utils.IdWorker;
import com.wnn.demo.utils.PageUtil;
import lombok.AllArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.mapper.util.StringUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/task")
@AllArgsConstructor
public class TaskController {

	private TaskService taskService;

	private Accessory accessory;

	private AccessoryService accessoryService;

	private FeedbackService feedbackService;

	private IdWorker idWorker;

	@Autowired
	private UserService userService;

	/**
	 * 文件上传
	 * @param file
	 * @return
	 */
	@PostMapping("/upload")
	public Result upload(MultipartFile file){

//		文件名
			String fileName = file.getOriginalFilename();
//		System.out.println("上传的文件名为：" + fileName);
			// 获取文件的后缀名
			String suffixName = fileName.substring(fileName.lastIndexOf("."));
//		System.out.println("上传的后缀名为：" + suffixName);
			// 文件上传后的路径
			String property = System.getProperty("user.dir");
//			String filePath = property+"/target/classes/picture/";
			String filePath = property+"/src/main/resources/public/picture/";
			String savePath = filePath+fileName;
			String path ="picture/" + fileName;
			File dest = new File(filePath + fileName);
			// 检测是否存在目录
			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdirs();
			}
			try {
				file.transferTo(dest);

			} catch (IOException e) {
				e.printStackTrace();
				return Result.error();
			}
		return new Result(ResultCode.OK,path);
	}

	/**
	 * 新建任务
	 * @param task
	 */
	@PostMapping("/newTask")
	public Result save(@RequestBody Task task){

		String id = idWorker.nextId() + "";
		Subject subject = SecurityUtils.getSubject();
		String username = (String) subject.getPrincipal();
		User user = userService.findUserByName(username);
		task.setId(id);
		task.setStatus(0);
		task.setIsDeleted(0);
		task.setTaskStatus(0);
		task.setCreateBy(username);
		task.setCreateTime(new Date());
		taskService.save(task);
		String hiddenFilePath = task.getHiddenFilePath();
		String[] split = hiddenFilePath.split(",");
		for (String s : split) {
			String idd = idWorker.nextId() + "";
			accessory.setId(idd);
			accessory.setAccessoryId(id);
			accessory.setFilePath(s);
			accessoryService.saveFile(accessory);
		}
		return Result.ok();
		// 获取文件名
	}

	/**
	 * 删除单个任务
	 * @param id
	 */
	@DeleteMapping("/deletedOne/{id}")
	public Result deleted(@PathVariable(value ="id") String id){
		Integer i = taskService.deletedOne(id);
		if (i>0){
			return Result.ok();
		}
		return Result.error();
	}

	/**
	 * 删除附件
	 * @param
	 */
	@PostMapping("/delFile/{id}")
//	@PostMapping("/delFile")
	public Result delFile(@PathVariable(value = "id")String id){
		System.out.println(id);
		accessoryService.deletedOne(id);
		return Result.ok();
	}

	/**
	 * 修改任务信息
	 * @param task
	 */
	@PutMapping("/updateTask/{id}")
	public Result updateTask(@PathVariable(value = "id") String id,@RequestBody Task task){
		task.setId(id);
		task.setUpdateTime(new Date());
		taskService.update(task);
		String hiddenFilePath = task.getHiddenFilePath();
		System.out.println(hiddenFilePath);
		String[] split = hiddenFilePath.split(",");
		if (split[0] == null){
			List<Accessory> files = accessoryService.findFile(task.getId());
			if (files.size()>0){
				for (Accessory file1 : files) {
					for (String s : split) {
						if (!file1.getFilePath().equals(s)){
							String idd = idWorker.nextId() + "";
							accessory.setId(idd);
							accessory.setAccessoryId(task.getId());
							accessory.setFilePath(s);
							accessoryService.saveFile(accessory);
						}
					}
				}
			}else{
				for (String s : split) {
					String idd = idWorker.nextId() + "";
					accessory.setId(idd);
					accessory.setAccessoryId(task.getId());
					accessory.setFilePath(s);
					accessoryService.saveFile(accessory);
				}
			}
		}
		return Result.ok();
	}


	/**
	 * 保存任务评价反馈信息
	 * @param feedback
	 * @param file
	 */
	@PostMapping("/saveFeedback")
	public void saveFeedback(Feedback feedback, @RequestParam("file") MultipartFile file){
		feedback.setId(IdGen.uuid());
		feedbackService.save(feedback);
		// 获取文件名
		String fileName = file.getOriginalFilename();
//		System.out.println("上传的文件名为：" + fileName);
		// 获取文件的后缀名
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
//		System.out.println("上传的后缀名为：" + suffixName);
		// 文件上传后的路径
		String property = System.getProperty("user.dir");
		String filePath = property+"/pic/";
		String savePath = filePath+fileName;
		File dest = new File(filePath + fileName);
		// 检测是否存在目录
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		try {
			file.transferTo(dest);
			accessory.setId(IdGen.uuid());
			accessory.setAccessoryId(feedback.getId());
			accessory.setFilePath(savePath);
			accessoryService.saveFile(accessory);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 任务列表
	 * @param page
	 * @param limit
	 * @return
	 */
	@GetMapping("/getAllTask")
	public Result findAll(@RequestParam(defaultValue = "1") Integer page,
						  @RequestParam(defaultValue = "10") Integer limit){
//		List<Task> list = taskService.findList();
////		PageUtil<Task> pageUtil = new PageUtil<>();
////		pageUtil.startPage(list,page,10);
////		return new Result(ResultCode.OK,pageUtil);
		PageInfo<Task> pageInfo  = taskService.selectTaskAll(page,limit);
		return new Result(ResultCode.OK,pageInfo.getTotal(),pageInfo.getList());
	}

	/**
	 * 任务审核列表
	 * @param pageNum
	 * @return
	 */
	@GetMapping("/getTask")
	public PageUtil<Task> findTask(Integer pageNum){
		List<Task> list = taskService.findAuditList();
		PageUtil<Task> pageUtil = new PageUtil<>();
		if (list.size()>0){
			pageUtil.startPage(list,pageNum,11);
			return pageUtil;
		}
		return pageUtil;
	}

	/**
	 * 任务下发列表
	 * @param pageNum
	 * @return
	 */
	@GetMapping("/getReleaseTask")
	public PageUtil<Task> findReleaseTask(Integer pageNum){
		List<Task> list = taskService.findReleaseTask();
		PageUtil<Task> pageUtil = new PageUtil<>();
		if (list.size()>0){
			pageUtil.startPage(list,pageNum,11);
			return pageUtil;
		}
		return pageUtil;
	}

	/**
	 * 提交审核任务
	 * @param task
	 */
    @PostMapping("/submit")
	public Result submit(Task task){
		task.setStatus(1);
		task.setApproveBeginTime(new Date());
		Integer i = taskService.submitId(task);
		if (i>0){
			return Result.ok();
		}else {
			return Result.error();
		}
	}

	/**
	 * 审核通过
	 * @param task
	 */
	@PostMapping("/audit")
	public void audit(Task task){
		task.setStatus(2);
		task.setApproveEndTime(new Date());
		taskService.submit(task);
	}

	/**
	 * 审核驳回
	 * @param task
	 */
	@PostMapping("/notAudit")
	public void notAudit(Task task){
		task.setStatus(3);
		task.setApproveEndTime(new Date());
		taskService.submit(task);
	}

	/**
	 * 根据名称查询任务
	 * @param task
	 * @return
	 */
	@GetMapping("/selectByName")
	public Task selectOne(Task task){
		Task task1 = taskService.selectOne(task);
		return task1;
	}

	/**
	 * 根据时间查询任务
	 * @param task
	 * @return
	 */
	@PostMapping("/selectByTime")
	public List<Task> selectByTime(Task task){
		System.out.println(task.getApproveEndTime());
		List<Task> task1 = taskService.selectByTime(task);
		return task1;
	}

	/**
	 * 查看任务详情
	 * @param task
	 * @return
	 */
	@GetMapping("/selectById")
	public Task selectById(Task task){
		Task task1 = taskService.selectOne(task);
		List<Accessory> file = accessoryService.findFile(task.getId());
		Feedback feedback = feedbackService.selectOne(task.getId());
		if (feedback != null){
			List<Accessory> file2 = accessoryService.findFile(feedback.getId());
			feedback.setAccessories(file2);
			System.out.println(feedback);
			task1.setFeedback(feedback);
		}
		task1.setAccessories(file);
		return task1;
	}
}

